/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.workcell.workdata.im.mvc.controller.system;

import com.workcell.workdata.im.model.response.ResponseEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * 公共http错误信息处理
 */
@ApiIgnore
@RestController
@RestControllerAdvice
@RequestMapping(value = "/error")
public class ServletErrorController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ServletErrorController.class);

	@ExceptionHandler(ConstraintViolationException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ResponseEntity<Void> handleError400(ConstraintViolationException violationException) {
		StringBuilder builder = new StringBuilder();
		for (ConstraintViolation<?> violation : violationException.getConstraintViolations()) {
			builder.append(violation.getMessageTemplate()).append(",");
		}
		return ResponseEntity.make(HttpStatus.BAD_REQUEST.value(), builder.deleteCharAt(builder.length() - 1).toString());
	}

	@ExceptionHandler(MissingServletRequestParameterException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ResponseEntity<Void> handleError400(MissingServletRequestParameterException exception) {
		return ResponseEntity.make(HttpStatus.BAD_REQUEST.value(), "缺少必要的参数:" + exception.getParameterName());
	}

	@ExceptionHandler(HttpMessageNotReadableException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ResponseEntity<Void> handleError400(HttpMessageNotReadableException ignore) {
		return ResponseEntity.make(HttpStatus.BAD_REQUEST.value(), "输入的数据格式不正确，请检查");
	}


	@RequestMapping(value = "/401")
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public ResponseEntity<Void> handleError401() {
		return ResponseEntity.make(HttpStatus.UNAUTHORIZED);
	}

	@RequestMapping(value = "/403")
	@ResponseStatus(HttpStatus.FORBIDDEN)
	public ResponseEntity<Void> handleError403() {
		return ResponseEntity.make(HttpStatus.FORBIDDEN);
	}

	@RequestMapping(value = "/404")
	@ExceptionHandler(NoHandlerFoundException.class)
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public ResponseEntity<Void> handleError404() {
		return ResponseEntity.make(HttpStatus.NOT_FOUND);
	}


	@RequestMapping(value = "/405")
	@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public ResponseEntity<Void> handleError405(HttpRequestMethodNotSupportedException exception) {
		return ResponseEntity.make(HttpStatus.METHOD_NOT_ALLOWED.value(), "请求method不支持,仅支持:" + StringUtils.join(exception.getSupportedMethods(),','));
	}

	@RequestMapping(value = "/415")
	@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
	@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
	public ResponseEntity<Void> handleError415(HttpMediaTypeNotSupportedException exception) {
		return ResponseEntity.make(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), "contentType不支持:" + exception.getContentType());
	}


	@RequestMapping(value = "/413")
	@ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
	@ExceptionHandler(MaxUploadSizeExceededException.class)
	public ResponseEntity<Void> handleError413(MaxUploadSizeExceededException exception) {
		return ResponseEntity.make(HttpStatus.PAYLOAD_TOO_LARGE.value(),"文件超过了最大限制:" + exception.getMaxUploadSize() +"字节");
	}


	@RequestMapping(value = "/500")
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(Exception.class)
	public ResponseEntity<Void> handleError500(Exception exception, HttpServletRequest request, HttpServletResponse response) {

		response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) ;

		LOGGER.error("请求处理异常,uri:{}",request.getRequestURI(),exception);

		return ResponseEntity.make(HttpStatus.INTERNAL_SERVER_ERROR);
	}
}
